package models.mappers;

import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import javax.sql.RowSet;
import java.io.Console;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
import java.sql.DriverManager;

import models.*;
import db.*;
import java.util.HashMap;
import voidlib.*;

/**
 * @author eliseev
 */
public class UserMapper  extends VoidMapper {
    
    public UserMapper() {
        super();
    }
    
    
  
    public static void CreateUser(int id, String login, String password, String title, int balance,UserRole role) throws SQLException
    {
        String str = null;
        try {
            str = String.format("insert into users (id ,login , pw ,title , balance ,role )  values (%d,'%s','%s','%s',%d,'%s')",id,login,password,title,balance,role.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DbConnector.Execute(str);
                
    }
    public User getUser (String login, String password) 
    {   
        HashMap<String, Object> where = new HashMap<String, Object>();
        where.put("login = ?", login);
        where.put("password = ?", password);
        return this.fetchOne(where);
    }
    
    public static User GetUser(int id) 
    {
        String str = String.format("SELECT * FROM users WHERE id=%d",id);
        try {
            ResultSet results = DbConnector.ExecuteQuery(str);
            ResultSetMetaData rsmd = results.getMetaData();
            if (results.next())
            {
                User user = new User(results.getString(2),results.getString(3),results.getString(4),results.getInt(5),UserRole.valueOf(results.getString(6)));
                
                user._id = id;
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        return null;
    }
    public static void UpdateUser(User user) 
    {
        String str = String.format("UPDATE users SET login='%s', pw='%s',title='%s',balance=%d, role='%s' WHERE id=%d",user.getLogin(),user.getPassword(),user.getTitle(),user.getBalance(),user.getRole().toString(), user.getId());
        int i= 0;
        i++;
        DbConnector.Execute(str);
    }
    public static void DeleteUser ( User user)
    {
        String str = String.format("Delete FROM users WHERE id = %d",user.getId());
        DbConnector.Execute(str);
    }

    @Override
    protected String _getTable() {
        return "users";
    }

    @Override
    protected String _getId() {
        return "id";
    }

    @Override
    protected Class<?> _getModel() {
        return User.class;
    }
    
}
